package com.dictionary.hi;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;
import com.inapp.util.BillingService;
import com.mango9x.utils.HttpHelpers;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;

public class ImagePagerViewController extends AbstractViewController {

	private MainTabHostActivity mainTabHostActivity;
	private ViewPager pager;
	private ImagePagerAdapter imagePagerAdapter;
	private DisplayImageOptions options;
	private String[] imageIDS;
	private String[] likes;
	private String[] dislikes;
	private String[] imageUrls;
	private View v;
	private Button imageViewFavoite;
	private BitmapDrawable favoriteDrawable;
	private BitmapDrawable unfavoriteDrawable;
	private boolean isFavorite;
	private int pagerPosition;

	@SuppressWarnings("deprecation")
	public ImagePagerViewController(AbstractTabRootManager tabRootManager,
			Bundle bundle) {
		super(tabRootManager, R.layout.vc_image_pager);
		try {
			mainTabHostActivity = (MainTabHostActivity) getActivity();
			mainTabHostActivity.hideTabWidget();
			mainTabHostActivity.hideTitleBar();
			v = getView();
			imageUrls = bundle.getStringArray(Extra.IMAGES);
			pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);

			imageIDS = bundle.getStringArray(Extra.IMAGE_IDS);
			likes = bundle.getStringArray(Extra.LIKES);
			dislikes = bundle.getStringArray(Extra.DISLIKES);

			options = new DisplayImageOptions.Builder()
					.showImageForEmptyUri(R.drawable.ic_launcher).cacheOnDisc()
					.displayer(new BitmapDisplayer() {

						public Bitmap display(Bitmap bitmap, ImageView imageView) {
							imageView.setAnimation(AnimationUtils
									.loadAnimation(mainTabHostActivity,
											R.anim.fade_in));
							imageView.setImageBitmap(bitmap);
							return bitmap;
						}
					}).imageScaleType(ImageScaleType.EXACTLY).build();

			pager = (ViewPager) v.findViewById(R.id.pager);
			imageViewFavoite = (Button) v.findViewById(R.id.ImageViewFavorite);

			favoriteDrawable = new BitmapDrawable(BitmapFactory.decodeResource(
					mainTabHostActivity.getResources(), R.drawable.favorite));
			unfavoriteDrawable = new BitmapDrawable(
					BitmapFactory.decodeResource(
							mainTabHostActivity.getResources(),
							R.drawable.unfavorite));

			isFavorite = mainTabHostActivity.getDatabaseAccessor().isFavorite(
					Integer.parseInt(imageIDS[pagerPosition]));
			if (isFavorite) {
				imageViewFavoite.setCompoundDrawablesWithIntrinsicBounds(null,
						null, favoriteDrawable, null);
			} else {
				imageViewFavoite.setCompoundDrawablesWithIntrinsicBounds(null,
						null, unfavoriteDrawable, null);
			}

			imagePagerAdapter = new ImagePagerAdapter(imageUrls, getActivity());
			pager.setAdapter(imagePagerAdapter);
			pager.setCurrentItem(pagerPosition);
			pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

				public void onPageSelected(int position) {
					try {
						pagerPosition = position;
						isFavorite = mainTabHostActivity
								.getDatabaseAccessor()
								.isFavorite(
										Integer.parseInt(imageIDS[pagerPosition]));
						if (isFavorite) {
							imageViewFavoite
									.setCompoundDrawablesWithIntrinsicBounds(
											null, null, favoriteDrawable, null);
						} else {
							imageViewFavoite
									.setCompoundDrawablesWithIntrinsicBounds(
											null, null, unfavoriteDrawable,
											null);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					Log.i("DREG", "POSITION=" + position);
				}

				public void onPageScrolled(int arg0, float arg1, int arg2) {
					// TODO Auto-generated method stub

				}

				public void onPageScrollStateChanged(int arg0) {
					// TODO Auto-generated method stub

				}
			});

			v.findViewById(R.id.ImageViewShare).setOnClickListener(
					new OnClickListener() {
						public void onClick(View v) {
							try {
								Bitmap bitmap = imagePagerAdapter
										.getBitmap(pager.getCurrentItem());
								ByteArrayOutputStream stream = new ByteArrayOutputStream();
								bitmap.compress(Bitmap.CompressFormat.JPEG,
										100, stream);
								String url = Images.Media.insertImage(
										getActivity().getApplicationContext()
												.getContentResolver(), bitmap,
										"title", null);
								Intent shareIntent = new Intent(
										Intent.ACTION_SEND);
								shareIntent
										.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
								shareIntent.putExtra(Intent.EXTRA_SUBJECT,
										"Check this out..");
								shareIntent.putExtra(Intent.EXTRA_STREAM,
										Uri.parse(url));
								shareIntent.setType("image/jpeg");
								startActivityForResult(shareIntent, 111);
							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					});

			v.findViewById(R.id.ImageViewSave).setOnClickListener(
					new OnClickListener() {

						public void onClick(View v) {
							// File dir = new
							// File(Environment.getExternalStorageDirectory().getPath()+"/"+getPackageName()+"/");
							File dir = new File(Environment
									.getExternalStorageDirectory().getPath()
									+ "/newimages/");
							dir.mkdirs();

							OutputStream fOut = null;
							File file = new File(dir.getPath(), ""
									+ new Date().getTime() + ".jpg");
							try {
								fOut = new FileOutputStream(file);
								// ImageView imageView = ((ImageView)
								// v.findViewById(4000+v.getId()));
								// Bitmap bitmap =
								// ((BitmapDrawable)imageView.getDrawable()).getBitmap();
								Bitmap bitmap = imagePagerAdapter
										.getBitmap(pager.getCurrentItem());

								bitmap.compress(Bitmap.CompressFormat.JPEG,
										100, fOut);
								fOut.flush();
								fOut.close();
								new SingleMediaScanner(getActivity(), file);
								Toast.makeText(
										getActivity(),
										"تم حفظ الصورة في "
												+ dir.getName(),
										Toast.LENGTH_LONG).show();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					});

			v.findViewById(R.id.ImageViewSetAsWallpaper).setOnClickListener(
					new OnClickListener() {
						public void onClick(View v) {

							try {
								Bitmap bitmap = imagePagerAdapter
										.getBitmap(pager.getCurrentItem());
								Display display = getActivity()
										.getWindowManager().getDefaultDisplay();
								int width = display.getWidth() * 2;
								int height = display.getHeight();
								bitmap = Bitmap.createScaledBitmap(bitmap,
										width, height, true);
								try {
									getActivity().getApplicationContext()
											.setWallpaper(bitmap);
									Toast.makeText(getActivity(),
											"تم تعيين خلفية الشاشة",
											Toast.LENGTH_LONG).show();
								} catch (IOException e) {
									Toast.makeText(getActivity(),
											"خطأ في تعيين الخلفية",
											Toast.LENGTH_LONG).show();
									e.printStackTrace();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});

			imageViewFavoite.findViewById(R.id.ImageViewFavorite)
					.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							try {

								int fileId = Integer
										.parseInt(imageIDS[pagerPosition]);
								if (isFavorite) {
									mainTabHostActivity.getDatabaseAccessor()
											.removeFromFavorites(fileId);
									mainTabHostActivity
											.sendBroadcastMessage(
													FavoritesViewController.KEY_FAVORITES_CHANGED,
													FavoritesViewController.REMOVED);
								} else {
									mainTabHostActivity.getDatabaseAccessor()
											.addToFavorites(fileId);
									mainTabHostActivity
											.sendBroadcastMessage(
													FavoritesViewController.KEY_FAVORITES_CHANGED,
													FavoritesViewController.ADDED);
								}
								isFavorite = !isFavorite;
								if (isFavorite) {
									imageViewFavoite
											.setCompoundDrawablesWithIntrinsicBounds(
													null, null,
													favoriteDrawable, null);
								} else {
									imageViewFavoite
											.setCompoundDrawablesWithIntrinsicBounds(
													null, null,
													unfavoriteDrawable, null);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onDestroy() {
		try {
			imagePagerAdapter.clearMap();
			mainTabHostActivity.showTitleBar();
			mainTabHostActivity.showTabWidget();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	// @Override
	// public void onDestroy() {
	// try {
	// mainTabHostActivity.getImageLoader().stop();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// super.onDestroy();
	// }

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;
		private SparseArray<ImageView> imageViews;

		ImagePagerAdapter(String[] images, Context context) {
			this.images = images;
			imageViews = new SparseArray<ImageView>();
			inflater = LayoutInflater.from(context);
		}

		public void clearMap() {
			try {
				imageViews.clear();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public Bitmap getBitmap(int position) {
			Bitmap ret = null;
			try {
				ret = ((BitmapDrawable) imageViews.get(position).getDrawable())
						.getBitmap();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return ret;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			try {
				imageViews.remove(position);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				((ViewPager) container).removeView((View) object);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(View view, final int position) {

			final LinearLayout imageLayout = (LinearLayout) inflater.inflate(
					R.layout.vc_item_pager_image, null);
			final ImageView imageView = (ImageView) imageLayout
					.findViewById(R.id.image);
			imageView.setAnimation(AnimationUtils.loadAnimation(
					mainTabHostActivity, R.anim.fade_in));
			imageView.setOnClickListener(new OnClickListener() {

				public void onClick(View vi) {
					Intent intent = new Intent(getActivity(),
							FullPageImageActivity.class);
					intent.putExtra("url", imageUrls[position]);
					getActivity().startActivity(intent);

				}
			});

			final ProgressBar spinner = (ProgressBar) imageLayout
					.findViewById(R.id.loading);
			Button likesTextView = (Button) imageLayout
					.findViewById(R.id.buttonLike);
			Button dislikesTextView = (Button) imageLayout
					.findViewById(R.id.buttonDislike);

			likesTextView.setText(likes[position]);
			dislikesTextView.setText(dislikes[position]);

			likesTextView.setOnClickListener(new OnClickListener() {

				public void onClick(final View v) {

					boolean isProVersion = BillingService.isPurchased(
							getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
							|| mainTabHostActivity.getPackageName().endsWith("pro");
					final String url = isProVersion ? getString(R.string.like_url_pro)
							: getString(R.string.like_url);
					new AlertDialog.Builder(getActivity())
							.setMessage("هل أعجبتك الصورة؟")
							.setCancelable(false)
							.setTitle("تقييم الصورة")
							.setPositiveButton("نعم",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											sendURLRequest(url
													+ imageIDS[position]);
											Toast.makeText(getActivity(),
													"تم  التقييم",
													Toast.LENGTH_LONG).show();
										}
									})
							.setNegativeButton("لا",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									}).show();

				}

			});

			dislikesTextView.setOnClickListener(new OnClickListener() {

				public void onClick(final View v) {
					boolean isProVersion = BillingService.isPurchased(
							getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
							|| mainTabHostActivity.getPackageName().endsWith("pro");
					final String url = isProVersion ? getString(R.string.dislike_url_pro)
							: getString(R.string.dislike_url);
					new AlertDialog.Builder(getActivity())
							.setMessage("لم تعجبك الصورة ؟")
							.setCancelable(false)
							.setTitle("تقييم الصورة")
							.setPositiveButton("نعم",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											sendURLRequest(url
													+ imageIDS[position]);
											Toast.makeText(getActivity(),
													"تم التقييم",
													Toast.LENGTH_LONG).show();
										}
									})
							.setNegativeButton("لا",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									}).show();

				}
			});

			Button errorImageView = (Button) imageLayout
					.findViewById(R.id.buttonError);
			errorImageView.setOnClickListener(new OnClickListener() {

				public void onClick(final View v) {
					boolean isProVersion = BillingService.isPurchased(
							getSharedPreferences(), Extra.IN_APP_PRODUCT_ID)
							|| mainTabHostActivity.getPackageName().endsWith("pro");
					final String url = isProVersion ? getString(R.string.error_url_pro)
							: getString(R.string.error_url);
					new AlertDialog.Builder(getActivity())
							.setMessage("هل تريد الإبلاغ عن الصورة؟")
							.setCancelable(false)
							.setTitle("خطأ في الصورة")
							.setPositiveButton("نعم",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											sendURLRequest(url
													+ imageIDS[position]);
											Toast.makeText(
													getActivity(),
													"تم الإرسال",
													Toast.LENGTH_LONG).show();
										}
									})
							.setNegativeButton("لا",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									}).show();

				}
			});

			mainTabHostActivity.getImageLoader().displayImage(
					images[position],
					imageView,
					options,
					new ImageLoadingListener() {
						public void onLoadingStarted(String imageUri, View view) {
							spinner.setVisibility(View.VISIBLE);
						}

						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							String message = null;
							switch (failReason.getType()) {
							case IO_ERROR:
								message = "Input/Output error";
								break;
							case OUT_OF_MEMORY:
								message = "Out Of Memory error";
								break;
							case UNKNOWN:
								message = "Unknown error";
								break;
							}
							Toast.makeText(getActivity(), message,
									Toast.LENGTH_SHORT).show();

							spinner.setVisibility(View.GONE);
							imageView
									.setImageResource(android.R.drawable.ic_delete);
						}

						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							spinner.setVisibility(View.GONE);
							imageViews.put(position, imageView);
						}

						public void onLoadingCancelled(String imageUri,
								View view) {
							// Do nothing
						}
					});
			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}

	private void sendURLRequest(final String url) {
		new AsyncTask<String, String, String>() {
			protected String doInBackground(String... arg0) {
				HttpHelpers.getJSONfromURL(url);
				return null;
			}
		}.execute();
	}

	public class SingleMediaScanner implements MediaScannerConnectionClient {

		private MediaScannerConnection mMs;
		private File mFile;

		public SingleMediaScanner(Context context, File f) {
			mFile = f;
			mMs = new MediaScannerConnection(context, this);
			mMs.connect();
		}

		public void onMediaScannerConnected() {
			mMs.scanFile(mFile.getAbsolutePath(), null);
		}

		public void onScanCompleted(String path, Uri uri) {
			mMs.disconnect();
		}

	}
}